﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WarehouseInsp.Buz.Interfaces;
using Microhard.Core.DBUtility;
using Microhard.WarehouseInsp.Buz.DataAccess;
using Microhard.WarehouseInsp.Buz.DTO;
using Microhard.Core;
using Microhard.WarehouseInsp.Buz.Msg;
using Microhard.WarehouseInsp.Buz.Models;
using Microhard.WarehouseInsp.Buz.BuzEnum;
using Microhard.WarehouseInsp.Buz.JHWorkflow;
using Microhard.JHWorkflowTrans;


namespace Microhard.WarehouseInsp.Buz.Impls
{
    public class SupProjectImpl : ISupProject
    {
        public List<PledgeChangeRecordModel> GetPledgeChangeRecords(Guid proid)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var PledgeList = db.PledgePlanInRecords.Where(n => n.ProjectID == proid);
            List<PledgeChangeRecordModel> PledgeChangeList = new List<PledgeChangeRecordModel>();

            foreach (var p in PledgeList)
            {
                List<PledgeChangeRecord> pc = db.PledgeChangeRecords.Where(n => n.PlnPdgID == p.PlnPdgID).OrderBy(n => n.CreateTime).ToList();

                if (pc.Count > 0)
                {
                    foreach (PledgeChangeRecord p1 in pc)
                    {
                        PledgeChangeRecordModel pledge = new PledgeChangeRecordModel();
                        pledge.PledgeProductID = p1.PledgeProductID;
                        pledge.PlnPdgID = p1.PlnPdgID;
                        pledge.CurrentCount = p1.CurrentCount;
                        pledge.CurrentAmount = p1.CurrentAmount;
                        pledge.CreateTime = p1.CreateTime;
                        pledge.CurrentPrice = p1.CurrentPrice;
                        pledge.IsUsing = p1.IsUsing;

                        PledgeChangeList.Add(pledge);
                    }
                }

            }
            return PledgeChangeList;
        }
        public List<SupProjectModel> GetAllSupProject()
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            IEnumerable<SupProject> entities = from b in db.SupProjects
                                               where b.ProjectID != Guid.Empty
                                               select b;

            if (entities.Count() > 0)
            {
                List<SupProjectModel> list = entities.Select(m => m.ToModel()).ToList();
                return list;
            }


            return new List<SupProjectModel>();
        }

        public Core.DBUtility.ExecutedResult Add(Models.SupProjectModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.SupProjects.SingleOrDefault(l => l.ProjectID == model.ProjectID);
            if (entity != null)
            {
                entity.Credit = model.Credit;
                entity.Guarantee = model.Guarantee;
                entity.PedgeeCompanyName = model.PedgeeCompanyName;
                entity.PedgeeContactor = model.PedgeeContactor;
                entity.PedgeeContactorPhone = model.PedgeeContactorPhone;
                entity.PrjEndTime = model.PrjEndTime;
                entity.PrjStartTime = model.PrjStartTime;
                entity.Rent = model.Rent;
                entity.SupervisionFee = model.SupervisionFee;
                entity.SupInsuranceCharge = model.SupInsuranceCharge;
                entity.UpdateTime = DateTime.Now;
                entity.Name = model.Name;
                entity.Code = model.Code;
                entity.PMID = model.PMID;
                entity.PMName = model.PMName;
                entity.ProtalEmpID = model.ProtalEmpID;
                entity.ProtalEmpName = model.ProtalEmpName;
                entity.Rate = model.Rate;
                entity.PrjType = model.PrjType;
                //修改法人信息
                var fr = entity.CustomerContracts.First(w => w.ContractType == (int)BrowserType.FR);
                fr.Name = model.MortgagorFRName;
                fr.IdentityNo = model.MortgagorFRIdentityNo;
                fr.Cellphone = model.MortgagorFRCellphone;
                //修改联系人信息
                var cnt = entity.CustomerContracts.First(w => w.ContractType == (int)BrowserType.Contract);
                cnt.Name = model.MortgagorContractorName;
                cnt.Cellphone = model.MortgagorContractorCellphone;
            }
            else
            {
                var op = model.ToEntity();
                op.CreateTime = DateTime.Now;
                op.UpdateTime = DateTime.Now;
                op.CreatorID = this.scope.CurrentUserID;
                op.CreatorName = this.scope.CurrentUserRealName;
                op.Status = (int)PrjStatus.Saved;
                //添加法人信息
                CustomerContract cc = new CustomerContract
                {
                    Cellphone = model.MortgagorFRCellphone,
                    ContractType = (int)BrowserType.FR,
                    CreateTime = DateTime.Now,
                    CustomerID = Guid.NewGuid(),
                    IdentityNo = model.MortgagorFRIdentityNo,
                    Name = model.MortgagorFRName,
                    SupPrjID = op.ProjectID
                };
                op.CustomerContracts.Add(cc);
                //添加联系人信息
                CustomerContract cc2 = new CustomerContract
                {
                    Cellphone = model.MortgagorContractorCellphone,
                    ContractType = (int)BrowserType.Contract,
                    CreateTime = DateTime.Now,
                    CustomerID = Guid.NewGuid(),
                    Name = model.MortgagorContractorName,
                    SupPrjID = op.ProjectID
                };
                op.CustomerContracts.Add(cc2);
                db.SupProjects.AddObject(op);
            }


            try
            {
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, SubProjectMsg.AddFailed);
                Log.Error("ISupProject.Add", ex);
            }
            return rtn;
        }

        public Core.DBUtility.ExecutedResult Update(Models.SupProjectModel model)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.SupProjects.SingleOrDefault(l => l.ProjectID == model.ProjectID
                && (l.Status == (int)PrjStatus.Saved || l.Status == (int)PrjStatus.Finished || l.Status == (int)PrjStatus.RollBack));
            if (entity != null)
            {
                entity.Credit = model.Credit;
                entity.Guarantee = model.Guarantee;
                entity.PedgeeCompanyName = model.PedgeeCompanyName;
                entity.PedgeeContactor = model.PedgeeContactor;
                entity.PedgeeContactorPhone = model.PedgeeContactorPhone;
                entity.PrjEndTime = model.PrjEndTime;
                entity.PrjStartTime = model.PrjStartTime;
                entity.Rent = model.Rent;
                entity.SupervisionFee = model.SupervisionFee;
                entity.SupInsuranceCharge = model.SupInsuranceCharge;
                entity.UpdateTime = DateTime.Now;
                entity.Name = model.Name;
                entity.Code = model.Code;
                entity.PMID = model.PMID;
                entity.PMName = model.PMName;
                entity.ProtalEmpID = model.ProtalEmpID;
                entity.ProtalEmpName = model.ProtalEmpName;
                entity.Rate = model.Rate;
                entity.PrjType = model.PrjType;
                //修改法人信息
                var fr = entity.CustomerContracts.First(w => w.ContractType == (int)BrowserType.FR);
                fr.Name = model.MortgagorFRName;
                fr.IdentityNo = model.MortgagorFRIdentityNo;
                fr.Cellphone = model.MortgagorFRCellphone;
                //修改联系人信息
                var cnt = entity.CustomerContracts.First(w => w.ContractType == (int)BrowserType.Contract);
                cnt.Name = model.MortgagorContractorName;
                cnt.Cellphone = model.MortgagorContractorCellphone;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, SubProjectMsg.UpdateFailed);
                Log.Error("IIspCategory.Update", ex);
            }
            return result;
        }

        public Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var toDelete = db.SupProjects.Where(e => ids.Contains(e.ProjectID)).ToList();
            toDelete.ForEach(e =>
            {
                //用户是否在使用
                if (e.Status == (int)PrjStatus.Saved)
                {
                    //删除附件
                    var delFiles = db.Attachments.Where(a => a.MainDataID == e.ProjectID);
                    foreach (var d in delFiles)
                    {
                        db.Attachments.DeleteObject(d);
                    }
                    //删除预警信息
                    var yj = db.SupervisionDetails.Where(s => s.ProjectID == e.ProjectID);
                    foreach (var y in yj)
                    {
                        db.SupervisionDetails.DeleteObject(y);
                    }
                    //删除质押物信息
                    var zy = db.PledgePlanInRecords.Where(p => p.ProjectID == e.ProjectID);
                    foreach (var z in zy)
                    {
                        db.PledgePlanInRecords.DeleteObject(z);
                    }
                    //删除联系人法人信息
                    var cctodel = db.CustomerContracts.Where(p => p.SupProject.ProjectID == e.ProjectID);
                    foreach (var c in cctodel)
                    {
                        db.CustomerContracts.DeleteObject(c);
                    }
                    //删除项目
                    db.SupProjects.DeleteObject(e);
                }
                else
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, string.Format(SubProjectMsg.IsInUsing, e.Name));
                }
            });
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, SubProjectMsg.DeleteFailed);
                    Log.Error("ISupProject.Delete", ex);
                }
            }
            return result;
        }

        public Core.DBUtility.ExecutedResult Delete(Models.SupProjectModel model)
        {
            throw new NotImplementedException();
        }

        public Models.SupProjectModel GetModelByID(Guid id)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.SupProjects.SingleOrDefault(e => e.ProjectID == id);
            if (entity != null)
            {
                var data = entity.ToModel();
                return data;
            }
            return null;
        }

        public Models.SupProjectModel GetModelByModel(Models.SupProjectModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.SupProjectModel> Query(Models.SupProjectModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            //如果是风控专员或数据中心专员登录
            IEnumerable<SupProject> entities = (from b in db.SupProjects
                                                where (b.CreatorID == this.scope.CurrentUserID
                                                || b.PMID == this.scope.CurrentUserID)
                                                select b).ToList();
            //如果是监管员登录
            if (scope.CurrentUserRoleNames.Contains(SysConst.SUPOTALROLENAME))
            {
                entities = (from b in db.SupProjects
                            from p in b.PledgePlanInRecords
                            where p.Warehouse.WarehouseMngID == this.scope.CurrentUserID
                            select b).Distinct();
            }
            else if (scope.CurrentUserRoleNames.Contains(SysConst.PROTALROLENAME))
            {
                //如果是巡查员
                entities = from b in db.SupProjects
                           where b.ProtalEmpID == this.scope.CurrentUserID
                           select b;
            }
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            totalCount = entities.Count();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<SupProjectModel>();
        }



        public List<Models.SupProjectModel> Query(Models.SupProjectModel Model)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            //如果是风控专员或数据中心专员登录
            IEnumerable<SupProject> entities = (from b in db.SupProjects
                                                where (b.CreatorID == this.scope.CurrentUserID
                                                || b.PMID == this.scope.CurrentUserID)
                                                select b).ToList();
            //如果是监管员登录
            if (scope.CurrentUserRoleNames.Contains(SysConst.SUPOTALROLENAME))
            {
                entities = (from b in db.SupProjects
                            from p in b.PledgePlanInRecords
                            where p.Warehouse.WarehouseMngID == this.scope.CurrentUserID
                            select b).Distinct();
            }
            else if (scope.CurrentUserRoleNames.Contains(SysConst.PROTALROLENAME))
            {
                //如果是巡查员
                entities = from b in db.SupProjects
                           where b.ProtalEmpID == this.scope.CurrentUserID
                           select b;
            }

            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).ToList();

            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<SupProjectModel>();
        }

        public Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }


        public bool IsApproving(Guid projectID)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.SupProjects.SingleOrDefault(s => s.ProjectID == projectID);
            if (entity == null)
                return false;
            if (entity.Status == (int)PrjStatus.Saved || entity.Status == (int)PrjStatus.Finished || entity.Status == (int)PrjStatus.RollBack)
                return false;
            return true;
        }

        public List<SupProjectModel> GetSupProjectsByWarehouse(Guid WarehouseId)
        {
            WarehouseInspEntities entity = new WarehouseInspEntities();
            var Projects = from sp in entity.SupProjects
                           from p in sp.PledgePlanInRecords
                           where p.WarehouseID == WarehouseId
                           select sp;

            if (Projects.Count() > 0)
            {

                List<SupProjectModel> list = Projects.ToList().Select(p => p.ToModel()).ToList();
                return list;

            }
            return new List<SupProjectModel>();
        }



        public bool IsDuplicateName(SupProjectModel model)
        {
            WarehouseInspEntities entity = new WarehouseInspEntities();
            var prj = entity.SupProjects.SingleOrDefault(c => c.Name == model.Name);
            if (prj == null)
                return false;
            if (prj.ProjectID == model.ProjectID)
                return false;
            return true;
        }

        public bool IsDuplicateCode(SupProjectModel model)
        {
            WarehouseInspEntities entity = new WarehouseInspEntities();
            var prj = entity.SupProjects.SingleOrDefault(c => c.Code == model.Code);
            if (prj == null)
                return false;
            if (prj.ProjectID == model.ProjectID)
                return false;
            return true;
        }


        public List<SupProjectModel> GetSupProjectByProtal(Guid protalUserID)
        {
            WarehouseInspEntities entity = new WarehouseInspEntities();
            var Projects = from sp in entity.SupProjects
                           where sp.ProtalEmpID == protalUserID
                           && sp.Status == (int)PrjStatus.Finished
                           select sp;

            if (Projects.Count() > 0)
            {

                List<SupProjectModel> list = Projects.ToList().Select(p => p.ToModel()).ToList();
                return list;

            }
            return new List<SupProjectModel>();
        }

        public ExecutedResult Start(Guid pkid, Guid wfInstanceID, string nextApprovers)
        {
            ExecutedResult rtn = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.SupProjects.SingleOrDefault(e => e.ProjectID == pkid);
            //保存于审批拒绝的数据可以重新发起审批流程
            if (entity != null && (entity.Status == (int)PrjStatus.Saved
                || entity.Status == (int)PrjStatus.Finished || entity.Status == (int)PrjStatus.RollBack))
            {
                rtn.ExecutedModel = entity.ToModel();
                entity.Status = (int)PrjStatus.Approving;
                entity.ApproverID = nextApprovers;
                //获得审批者姓名
                var user = JHWorkflowTool.GetUserByID(nextApprovers);
                if (user != null)
                {
                    entity.ApproverName = user.Name;
                }
                rtn.NextApprovers = nextApprovers;
                //警戒信息变更状态
                foreach (var e in entity.SupervisionDetails.Where(x => x.Status == (int)PrjStatus.Saved
                    || x.Status == (int)PrjStatus.RollBack))
                {
                    e.Status = (int)PrjStatus.Approving;
                }
                //质押物信息变更状态
                foreach (var e in entity.PledgePlanInRecords.Where(x => x.Status == (int)PrjStatus.Saved
                    || x.Status == (int)PrjStatus.RollBack))
                {
                    e.Status = (int)PrjStatus.Approving;
                }
            }
            else
            {
                rtn.ExecutedModel = null;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error("ISupProject.Start", ex);
            }
            return rtn;
        }
    }
}
